package pers.qianyu.month_202011.date_20201120;

/**
 * 654. 最大二叉树
 * https://leetcode-cn.com/problems/maximum-binary-tree/
 *
 * @author mizzle rain
 * @date 2020-11-20 17:52
 */
public class ConstructMaximumBinaryTree {
    public TreeNode constructMaximumBinaryTree(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return recur(nums, 0, nums.length - 1);
    }

    private TreeNode recur(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        int val = nums[left];
        int index = left;
        for (int i = left; i <= right; i++) {
            if (val < nums[i]) {
                val = nums[i];
                index = i;
            }
        }
        TreeNode node = new TreeNode(val);
        node.left = recur(nums, left, index - 1);
        node.right = recur(nums, index + 1, right);
        return node;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
}
